package com.example.medicine.controller;

import com.example.medicine.Bean.*;
import com.example.medicine.Mapper.fjglMapper;
import com.example.medicine.Mapper.yonghuMapper;
import com.example.medicine.Mapper.zhongyaoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
@Slf4j
@RestController
@RequestMapping(value="/fjgl")
public class fjglController {
    @Autowired
    fjglMapper fjglMapper;
    @Autowired
    zhongyaoMapper zhongyaoMapper;
    @Autowired
    private yonghuMapper yonghuMapper;
    private int p;
    Subject subject = SecurityUtils.getSubject();
    @RequiresPermissions("方剂管理")
    @GetMapping("/")
    public List<jingfangWithCompany> getfjglList() {
        log.info("getfjglList获取方剂信息");
        yonghu yonghu = yonghuMapper.getById(subject.getPrincipal().toString());
        if(yonghu.getType().equals("中药+方剂录入")){
            return fjglMapper.getByUser(subject.getPrincipal().toString());
        }
        // 从数据库中获取数据
        return fjglMapper.getAll();
    }
//    @RequiresPermissions("方剂管理")
//    @GetMapping("/{id}")
//    public jingfang getfjglList1(@PathVariable int id) {
//        // 从数据库中获取数据
//        return fjglMapper.getById1(id);
//    }
    @RequiresPermissions("方剂管理")
    @GetMapping("/pf/{id}")
    public List<jingfang_peifang> getfjglList2(@PathVariable int id) {
        log.info("getfjglList2获取方剂的配方信息");
        // 从数据库中获取数据
        return fjglMapper.getAll2(id);
    }
    @RequiresPermissions("方剂管理")
@GetMapping("/yaowu")
    public List<zhongyao> getyaoming() {
        log.info("getyaoming获取中药名称");
        // 从数据库中获取数据
        return zhongyaoMapper.getzhongyao();
    }

    /**
     * 接收新建请求，向fjgl表中插入数据
     */
    @RequiresPermissions("方剂管理")
    @PostMapping("/")
    public void insertfjgl1(@RequestBody jingfang jingfang){
        log.info("insertfjgl1方剂添加start");
        jingfang.setCreateuser(subject.getPrincipal().toString());
        fjglMapper.insert1(jingfang);
        p=jingfang.getId();
        log.info("insertfjgl1方剂添加end");
    }
    @RequiresPermissions("方剂管理")
    @PostMapping("/pf/")
    public void insertfjgl2(@RequestBody jingfang_peifang jingfang_peifang){
        log.info("insertfjgl1方剂的配方插入(编辑)");
        fjglMapper.insert2(jingfang_peifang);}
    @RequiresPermissions("方剂管理")
    @PostMapping("/pf1/")
    public void insertfjgl3(@RequestBody jingfang_peifang jingfang_peifang){
        log.info("insertfjgl1方剂的配方插入(创建)");
        jingfang_peifang.setJingfang(p);
        fjglMapper.insert2(jingfang_peifang);}

    /**
     * 接收更新请求，根据id值更新fjgl表内容
     */
    @RequiresPermissions("方剂管理")
    @PutMapping("/")
    public void updatefjgl1(@RequestBody jingfang jingfang){
        log.info("updatefjgl1修改方剂start");
        fjglMapper.update1(jingfang);
        log.info("updatefjgl1修改方剂end");
    }
    @RequiresPermissions("方剂管理")
    @PutMapping("/pf1")
    public void updatefjgl2(@RequestBody jingfang_peifang jingfang_peifang){
        log.info("updatefjgl2修改方剂的配方");
        fjglMapper.update2(jingfang_peifang);
    }
    @RequiresPermissions("方剂管理")
    @PutMapping("/pf2")
    public void updatefjgl3(@RequestBody jingfang_peifang jingfang_peifang){
        log.info("updatefjgl3修改方剂的配方");
        fjglMapper.update3(jingfang_peifang);
    }
    @RequiresPermissions("方剂管理")
    @PostMapping("/batch/")
    public ResponseEntity<String> insertBatchfjgl(@RequestParam("file") MultipartFile file) {
        log.info("insertBatchfjgl方剂批量导入");
        try {
            // 校验文件类型，只接受 .xls 和 .xlsx 格式的文件
            if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported file format. Please upload an Excel file.");
            }

            List<jingfang> jfList = new ArrayList<>();
            // 使用 Apache POI 解析 Excel 文件并提取数据
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) { // 跳过表头行
                    continue;
                }
                jingfang jf = new jingfang();
                for(int i=0;i<=13;++i){
                    String value=null;
                    Cell cell= row.getCell(i);
                    if(cell!=null){
                        CellType cellType=cell.getCellType();
                        value = switch (cellType) {
                            case STRING ->
                                // 处理字符串类型的单元格
                                    cell.getStringCellValue();
                            case NUMERIC ->
                                // 处理数值类型的单元格
                                    String.valueOf((int)cell.getNumericCellValue());
                            default -> null;
                        };
                    }
                    switch (i) {
                        case 0 -> jf.setJingfangming(value);
                        case 1 -> jf.setLaiyuan(value);
                        case 2 -> jf.setLeixing(value);
                        case 3 -> jf.setJixing(value);
                        case 4 -> jf.setFanglun(value);
                        case 5 -> jf.setYongfayongliang(value);
                        case 6 -> jf.setJinguzhi(value);
                        case 7 -> jf.setFangjimingyi(value);
                        case 8 -> jf.setChaodai(value);
                        case 9 -> jf.setLiupai(value);
                        case 10 -> jf.setGongneng(value);
                        case 11 -> jf.setZhuzhi(value);
                        case 12 -> jf.setZhuzhizhengzhuang(value);
                        case 13 -> jf.setJinji(value);
                    }

                }
                jf.setCreateuser(subject.getPrincipal().toString());
                jfList.add(jf);
            }
            // 将数据批量插入数据库
            if (!jfList.isEmpty()) {
                fjglMapper.batchInsertjingfang(jfList);
                System.out.println("成功！");
            }
            return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
        } catch (Exception e) {
            e.printStackTrace(); // 添加错误日志
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\": \"发生错误！请联系管理员！\"}");
        }
    }
    @RequiresPermissions("方剂管理")
    @PutMapping("/shenhe")
    public void updateShenhe(@RequestBody jingfang jingfang){
        log.info("updateShenhe方剂审核");
        jingfang.setShr(subject.getPrincipal().toString());
        fjglMapper.updateShenhe(jingfang);
    }
    @RequiresPermissions("方剂管理")
    @DeleteMapping("/{id}")
    public void deletefjgl1(@PathVariable int id){
        log.info("deletefjgl1方剂删除");
        fjglMapper.deleteById1(id);
    }
    @RequiresPermissions("方剂管理")
    @DeleteMapping("/pf/{id}")
    public void deletefjgl2(@PathVariable int id){
        log.info("deletefjgl2方剂的配方删除");
        fjglMapper.deleteById2(id);
    }
}
